#include <iostream>
#include <string>
#include <stdio.h>
#include <mutex>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "Mutex.hpp"

using namespace MutexModule;

// // C++实现互斥量的简单封装
// int ticket = 100;
// std::mutex cpp_lock; // 定义锁

// void *route(void *arg)
// {
//     char *id = (char *)arg;
//     while (1)
//     {
//         cpp_lock.lock();
//         // pthread_mutex_lock(&lock); // 加锁
//         if (ticket > 0) // 逻辑计算->也要加锁
//         {
//             usleep(1000);
//             printf("%s sells ticket:%d\n", id, ticket);
//             ticket--; // 解锁
//             cpp_lock.unlock();
//         }
//         else
//         {
//             cpp_lock.unlock(); // 解锁
//             break;
//         }
//     }
//     return nullptr;
// }
// int main(void)
// {
//     pthread_t t1, t2, t3, t4;

//     pthread_create(&t1, NULL, route, (void *)"thread 1");
//     pthread_create(&t2, NULL, route, (void *)"thread 2");
//     pthread_create(&t3, NULL, route, (void *)"thread 3");
//     pthread_create(&t4, NULL, route, (void *)"thread 4");

//     pthread_join(t1, NULL);
//     pthread_join(t2, NULL);
//     pthread_join(t3, NULL);
//     pthread_join(t4, NULL);
// }
/////////////////////////////////////////////////////////////////

int ticket = 10;

class ThreadData
{
public:
    ThreadData(const std::string &n, Mutex &lock)
        : name(n),
          lockp(&lock)
    {
    }
    std::string name;
    // pthread_mutex_t *lockp;
    Mutex *lockp;
};

void *route(void *arg)
{
    ThreadData *td = static_cast<ThreadData *>(arg);
    while (1)
    {
        { // 封装代码块
            // 加锁完成, 出代码块时自动解锁
            LockGuard guard(*td->lockp); // RAII风格的互斥锁的实现
            if (ticket > 0)
            {
                usleep(1000);
                printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
                ticket--;
            }
            else
            {
                break;
            }
        }

        // td->lockp->Lock();
        // if (ticket > 0) // 逻辑计算->也要加锁
        // {
        //     usleep(1000);
        //     printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
        //     ticket--;
        //     td->lockp->Unlock();
        // }
        // else
        // {
        //     td->lockp->Unlock();
        //     break;
        // }
    }
    return nullptr;
}
int main(void)
{
    Mutex lock;
    pthread_t t1, t2, t3, t4;

    ThreadData *td1 = new ThreadData("thread-1", lock);
    pthread_create(&t1, NULL, route, td1);

    ThreadData *td2 = new ThreadData("thread-2", lock);
    pthread_create(&t2, NULL, route, td2);

    ThreadData *td3 = new ThreadData("thread-3", lock);
    pthread_create(&t3, NULL, route, td3);

    ThreadData *td4 = new ThreadData("thread-4", lock);
    pthread_create(&t4, NULL, route, td4);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);
}
